﻿using Microsoft.SharePoint;
using NLog;
using System;
using Microsoft.SharePoint.Navigation;
using SharePoint.Utility.Logging;

namespace CopyOrdersList.BL.Helpers
{
    public class NavigationHelper {

        static ILogger logger = DetailLog.GetLogger;

        public static void ReplaceListInNavigation(SPWeb web, SPList sourceList, SPList newList) {
            try {
                string url = newList.ParentWebUrl + "/" + newList.RootFolder;
                SPNavigationNode oldNode = web.Navigation.GetNodeByUrl(sourceList.ParentWebUrl + "/" + sourceList.RootFolder);
                if (oldNode != null) {
                    string resx = getTitle(oldNode.TitleResource) ?? oldNode.Title;                  
                    SPNavigationNode newNode = new SPNavigationNode(resx, url, true);
                    web.Navigation.QuickLaunch.Add(newNode, oldNode);
                    web.Navigation.QuickLaunch.Delete(oldNode);
                    web.Update();
                }
            }
            catch (Exception ex) {
                logger.Error(ex.ToString());
            }
        }

        private static string getTitle(SPUserResource resources) {
            string resx = null;
            if (resources != null) {
                resx = (string)ReflectionExtensions.GetFieldValue(resources, "ResxResourceId");
            }
            return resx;
 
        }
    }
}
